<template>
  <div class="enterprise-checkin-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <el-form inline :model="searchForm" class="search-form">
        <el-form-item label="企业名称">
          <el-autocomplete style="width: 250px" v-model="searchForm.enterpriseName" placeholder="请输入企业名称"
            :fetch-suggestions="queryEnterprise" :trigger-on-focus="false" clearable @select="handleSelectEnterprise" />
        </el-form-item>
        <el-form-item label="所属园区">
          <el-select v-model="searchForm.parkId" placeholder="请选择园区" @change="handleSelectParkIdChange" clearable
            style="width: 200px">
            <el-option v-for="park in parkData" :key="park.id" :label="park.name" :value="park.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属楼栋">
          <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" @change="handleSelectBuildIdChange" clearable
            style="width: 200px">
            <el-option v-for="building in parkBuildingData" :key="building.id" :label="building.name"
              :value="building.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼层">
          <el-select v-model="searchForm.floor" placeholder="请选择楼栋" @change="handleSelectRoomIdChange" clearable
            style="width: 200px">
            <el-option v-for="room in roomData" :key="room" :label="room" :value="room"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="openAddDialog">
            新增入住信息
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="roomDataList" :border="true" style="width: 100%; margin-top: 20px">
      <el-table-column prop="enterpriseName" label="企业名称" :align="center" width="220" />
      <el-table-column label="所属园区" :align="center" min-width="150">
        <template #default="scope">
          {{ scope.row.parkInfo?.name || '无数据' }}
        </template>
      </el-table-column>
      <el-table-column label="楼栋" :align="center" width="150">
        <template #default="scope">
          <el-tag class="mr-2">
            {{ scope.row.parkBuilding?.name || '无数据' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="楼层/房间" :align="center" width="250">
        <template #default="scope">
          <el-tag v-for="(room, index) in scope.row.enterpriseRoomPojos || []" :key="index" type="success" size="small"
            class="mr-2">
            {{ room.parkRoom.floor }}层-{{ room.parkRoom.roomNumber }}
            使用面积{{ room.enterpriseUseArea }}
            物业面积{{ room.enterprisePropertyArea }}
          </el-tag>
          <el-tag v-if="!scope.row.enterpriseRoomPojos || scope.row.enterpriseRoomPojos.length === 0">
            无数据
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用总面积" :align="center" width="150">
        <template #default="scope">
          <el-tag v-if="Array.isArray(scope.row.enterpriseRoomPojos) && scope.row.enterpriseRoomPojos.length > 0"
             type="success" size="small" class="mr-2">
            {{ getArea(scope.row.enterpriseRoomPojos, 1) }}
          </el-tag>
          <el-tag v-if="!scope.row.enterpriseRoomPojos || scope.row.enterpriseRoomPojos.length === 0">
            无数据
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物业总面积" :align="center" width="150">
        <template #default="scope">
          <el-tag v-if="Array.isArray(scope.row.enterpriseRoomPojos) && scope.row.enterpriseRoomPojos.length > 0"
             type="success" size="small" class="mr-2">
            {{ getArea(scope.row.enterpriseRoomPojos, 2) }}
          </el-tag>
          <el-tag v-if="!scope.row.enterpriseRoomPojos || scope.row.enterpriseRoomPojos.length === 0">
            无数据
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" :align="center" fixed="right">
        <template #default="scope">
          <!-- <el-button size="small" @click="handleView(scope.row)">查看</el-button> -->
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="page.currentPage" :page-sizes="[10, 20, 50]" :page-size="page.size"
      layout="total, sizes, prev, pager, next, jumper" :total="page.total" />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" :draggable="true"
      :close-on-click-modal="false">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <!-- 其他表单项保持不变 -->
        <el-form-item label="企业名称" prop="enterpriseId">
          <el-select v-model="form.enterpriseId" filterable placeholder="请选择企业名称" clearable>
            <el-option v-for="item in enterpriseData" :key="item.enterpriseId" :label="item.enterpriseName"
              :value="item.enterpriseId" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属园区" prop="parkId">
          <el-select v-model="form.parkId" placeholder="请选择园区" @change="handleSelectParkIdChange" clearable>
            <el-option v-for="park in parkData" :key="park.id" :label="park.name" :value="park.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属楼栋" prop="buildingId">
          <el-select v-model="form.buildingId" placeholder="请选择楼栋" @change="handleSelectBuildIdChange"
            :disabled="!form.parkId" clearable>
            <el-option v-for="building in parkBuildingData" :key="building.id" :label="building.name"
              :value="building.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择楼层" prop="floorIds">
          <el-button type="primary" plain @click="clickRoom" :disabled="!form.buildingId" clearable>选择房间</el-button>
        </el-form-item>
        <div style="text-align: left;margin-left: 10%;">
          <el-tag v-for="(room, index) in roomTags" :key="room.id" closable class="tag-item"
            @close="handleClose(room.id)">
            <span style="color: brown;">
              {{ room.floor }}
            </span>
            层
            <span style="color: brown;">
              {{ room.roomNumber }}
            </span>
            使用面积:
            <span style="color: brown;">
              {{ room.area }}
            </span>
            ㎡
            物业面积:
            <span style="color: brown;">
              {{ room.propertyArea }}
            </span>
            ㎡
            用途:
            <span style="color: brown;">
              {{ room.enterpriseRoomPojo.enterpriseRoomUsage }}
            </span>
          </el-tag>
        </div>

      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>


    <el-dialog title="选择房间信息" v-model="roomDialogVisible" :close-on-click-modal="false" width="70%" :draggable="true">
      <!-- 房间选择列表 -->
      <el-form-item label="已选楼层:" prop="floorIds">
        <el-tag v-for="(room, index) in roomTags" :key="room.id" closable class="tag-item"
          @close="handleClose(room.id)">
          <span style="color: brown;">
            {{ room.floor }}
          </span>
          层
          <span style="color: brown;">
            {{ room.roomNumber }}
          </span>
          使用面积:
          <span style="color: brown;">
            {{ room.area }}
          </span>
          ㎡
          物业面积:
          <span style="color: brown;">
            {{ room.propertyArea }}
          </span>
          ㎡
          用途:
          <span style="color: brown;">
            {{ room.enterpriseRoomPojo.enterpriseRoomUsage }}
          </span>
        </el-tag>
      </el-form-item>

      <el-form inline :model="filterForm" class="filter-form">
        <el-form-item label="楼层">
          <el-select v-model="filterForm.floor" placeholder="请选择楼栋" @change="handleEditSelectRoomIdChange" clearable
            style="width: 200px">
            <el-option v-for="room in roomData" :key="room" :label="room" :value="room"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <span style="color: indianred;">提示：如使用面积和物业面积需要修改请直接修改</span>
        </el-form-item>

        <el-table :data="roomDataEditList" ref="tableRef" :border="true" style="width: 100%;height: 300px;"
          @selection-change="handleSelectionChange" @row-click="handleRowClick" row-key="id">
          <el-table-column prop="id" type="selection" label="序号" style="width: 55;" :align="center" />
          <el-table-column prop="roomNumber" label="房间号" :align="center" min-width="100" />
          <el-table-column label="楼层" prop="floor" :align="center" min-width="100">
            <template #default="scope">
              {{ scope.row.floor }}
            </template>

          </el-table-column>
          <el-table-column label="使用面积(m²)" prop="area" :align="center" min-width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.area" type="number" size="small" placeholder="使用面积(m²)"
                @click.stop></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物业面积(m²)" prop="propertyArea" :align="center" min-width="100">
            <template #default="scope">
              <el-input v-model.number="scope.row.propertyArea" type="number" size="small" placeholder="物业面积(m²)"
                @click.stop></el-input>
            </template>
          </el-table-column>
          <el-table-column label="房间用途" prop="enterpriseRoomPojo.enterpriseRoomUsage" :align="center" min-width="150">
            <template #default="scope">
              <el-select v-model="scope.row.enterpriseRoomPojo.enterpriseRoomUsage" size="small" placeholder="请选择房间用途"
                @click.stop>
                <!-- 选项的value需与初始值匹配，才能显示对应label -->
                <el-option label="办公" value="办公"></el-option>
                <el-option label="展厅" value="展厅"></el-option>
                <el-option label="研发" value="研发"></el-option>
                <el-option label="会议" value="会议"></el-option>
                <el-option label="仓储" value="仓储"></el-option>
                <el-option label="培训" value="培训"></el-option>
                <el-option label="接待" value="接待"></el-option>
                <el-option label="创意" value="创意"></el-option>
                <el-option label="数据中心" value="数据中心"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>

            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" :align="center" min-width="150" />
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="roomDialogVisible = false">选择完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, getCurrentInstance  } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import request from '@/api/request'
import auth from '@/components/utils/auth'
defineEmits(['callUpdateLoadAnalysisMethod']); 
// 获取组件实例（用于 emit 事件）
const { emit } = getCurrentInstance();


const center = 'center'
const props = defineProps({
  parkData: {
    type: Object,
    default: () => ([])
  }
});
const searchForm = ref({
  enterpriseName: null,
  parkId: null,
  buildingId: null,
  floor: null
})
// 园区、楼栋、楼层数据保持不变
const parkData = props.parkData;

//企业下拉数据列表
const enterpriseData = ref([]);

const roomData = ref([]);
//楼栋筛选下拉框
const parkBuildingData = ref([])

// 入住信息列表（房间信息会包含更多详情）
const roomDataList = ref([]);
// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 1
})

//表单规则
const rules = {
  enterpriseId: [
    { required: true, message: '请输入企业全称', trigger: 'blur' }
  ],
  parkId: [
    { required: true, message: '请选择所属园区', trigger: 'blur' }
  ],
  buildingId: [
    { required: true, message: '请选择所属楼栋', trigger: 'blur' }
  ],
};
const userId = ref(null)
// 初始化数据
onMounted(() => {
  //加载房间数据表格
  loadRoomData()
  //查询新增编辑企业下拉
  loadEnterpriseData()
  try {
    const userInfo = auth.getUserInfo()
    userId.value = userInfo.id
  } catch (err) {

  }
});
//查询新增编辑企业下拉
const loadEnterpriseData = async (name) => {
  const res = await request.get("enterpriseRoom/getEnterpriseNameData", {
    params: { enterpriseName: name }  // 传递搜索关键词
  })
  if (res.success) {
    enterpriseData.value = res.data
  } else {
    enterpriseData.value = []
  }
}

//加载房间数据表格
const loadRoomData = async () => {
  // const loading = ElLoading.service({
  //   lock: true,
  //   text: '正在初始化页面数据...',
  //   background: 'rgba(0, 0, 0, 0.7)',
  // })
  try {
    const resData = await request.get('/enterpriseRoom/getEnterpriseRoomPage', {
      params: {
        pageNum: page.value.current,
        pageSize: page.value.size,
        enterpriseName: searchForm.value.enterpriseName,
        parkId: searchForm.value.parkId,
        buildingId: searchForm.value.buildingId,
        floor: searchForm.value.floor,
        enterpriseStatus: searchForm.value.selectedValue,
        enterpriseIsFollowed: searchForm.value.isFollowed
      }
    })
    if (resData.success) {
      roomDataList.value = resData.data.list
      page.value.total = resData.data.total
    }
  } catch (err) {

  } finally {
    // loading.close()
  }
}
// 分页-每页条数改变
const handleSizeChange = (val) => {
  page.value.size = val
}

// 分页-当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
}

// 处理园区选中变化
const handleSelectParkIdChange = (value) => {
  searchForm.value.buildingId = null
  searchForm.value.floor = null
  if (value) {
    loadRoomData()
    //查询楼栋信息
    getBuildIngInfo(value)
  } else {
    loadRoomData()
    roomData.value = []
    //楼栋筛选下拉框
    parkBuildingData.value = []
  }
};
//查询楼栋信息
const getBuildIngInfo = async (value) => {
  const data = await request.get("park-building/getParkBuildingByEnterpriseId", {
    params: {
      enterpriseId: value
    }
  })
  if (data.success) {
    parkBuildingData.value = data.data
  }
}
//楼栋选择
const handleSelectBuildIdChange = (value) => {
  searchForm.value.floor = null
  if (value) {
    loadRoomData()
    //查询楼层
    getParkRoom(value)
    roomDataEditList.value = []
    filterForm.value.floor = ''
  } else {
    loadRoomData()
    roomData.value = []
  }

}
//查询楼层
const getParkRoom = async (value) => {
  const data = await request.get("parkRoom/getParkFloorByBuildindId", {
    params: {
      buildingId: value
    }
  })
  if (data.success) {
    roomData.value = data.data
  }
}
//楼层选择
const handleSelectRoomIdChange = (value) => {
  loadRoomData()
}

const searchTimer = ref(null)  // 防抖计时器（ref 用于响应式存储）

/**
 * 输入时触发：请求后端接口获取匹配的企业列表
 * @param {string} queryString - 当前输入内容
 * @param {Function} callback - 回传下拉数据的回调
 */

const queryEnterprise = (queryString, callback) => {
  // 清除上一次的定时器（防抖）
  clearTimeout(searchTimer.value)

  // 300ms 防抖：输入停止后再请求
  searchTimer.value = setTimeout(async () => {
    // 输入为空时不请求
    if (!queryString.trim()) {
      callback([])
      return
    }
    try {
      const res = await request.get("enterpriseRoom/getEnterpriseNameData", {
        params: { enterpriseName: queryString }  // 传递搜索关键词
      })
      if (res.success) {
        if (res.data.length == 0) {
          callback([])
          return
        }
        // 格式化数据：下拉框需要 { value: '显示文本', ...其他字段 } 结构
        const suggestions = res.data.map(enterprise => ({
          value: enterprise.enterpriseName,  // 下拉框中显示的企业名称
          id: enterprise.enterpriseId,       // 企业ID（可选，用于后续业务）
          // 可添加其他需要的字段（如地址、代码等）
        }));
        // 将数据回传给下拉框
        callback(suggestions)
      } else {
        callback([])  // 出错时返回空数组
      }

    } catch (error) {
      console.error('获取企业列表失败：', error)
      callback([])  // 出错时返回空数组
    }
  }, 300)
}

/**
 * 选中下拉项时触发
 * @param {Object} item - 选中的企业对象（包含 value、id 等字段）
 */
const handleSelectEnterprise = (item) => {
  searchForm.enterpriseName = item.value
  loadRoomData()
}

//重置搜索表单
const resetSearch = () => {
  searchForm.value = {}
  roomData.value = []
  //楼栋筛选下拉框
  parkBuildingData.value = []
  loadRoomData()
};

// 搜索按钮逻辑
const handleSearch = () => {
  loadRoomData()
}

//计算面积 type：1使用面积，2：物业面积
const getArea = (rows, type) => {
  // 若数组不存在或为空，返回0
  if (!Array.isArray(rows) || rows.length === 0) return 0;
  // 累加所有area值（自动转换为数字，非数字按0处理）
  if (type == 1) {
    return rows.map(item => Number(item.enterpriseUseArea) || 0)
      .reduce((total, current) => total + current, 0).toFixed(2);
  }
  return rows.map(item => Number(item.enterprisePropertyArea) || 0)
    .reduce((total, current) => total + current, 0).toFixed(2);
}
// 弹窗状态和表单数据保持不变
const dialogVisible = ref(false);
const dialogTitle = ref('新增入住信息');
const formRef = ref(null);
//打开新增框
const openAddDialog = () => {
  resetForm();
  dialogTitle.value = '新增入住信息';
  dialogVisible.value = true;
};
//编辑方法
const handleEdit = (row) => {
  resetForm()
  dialogTitle.value = '编辑入住信息';
  dialogVisible.value = true;
  loadEnterpriseData(row.enterpriseName)
  form.parkId = row.parkInfo.id
  getBuildIngInfo(row.parkInfo.id)
  getParkRoom(row.parkBuilding.id)
  form.enterpriseId = row.enterpriseId
  form.buildingId = row.parkBuilding.id
  form.enterpriseRoomPojo = row.enterpriseRoomPojos
  row.enterpriseRoomPojos.forEach(item => {
    roomTags.value.push({
      area: item.enterpriseUseArea,
      buildingId: row.parkBuilding.id,
      createTime: item.createdAt,
      description: item.parkRoom.description,
      floor: item.parkRoom.floor,
      id: item.parkRoom.id,
      isDeleted: item.isDeleted,
      propertyArea: item.enterprisePropertyArea,
      roomNumber: item.parkRoom.roomNumber,
      status: item.parkRoom.status,
      updateTime: item.updatedAt,
      enterpriseRoomPojo: {
        enterpriseRoomUsage: item.enterpriseRoomUsage,
      }
    });
  })

}

const form = reactive({
  enterpriseId: '',
  parkId: null,
  buildingId: null,
  enterpriseRoomPojo: []
});
//清空表单
const resetForm = () => {
  form.enterpriseId = '';
  form.parkId = null;
  form.buildingId = null;
  form.enterpriseRoomPojo = [];
  roomTags.value = []
  roomDataEditList.value = []
  if (formRef.value) {
    formRef.value.resetFields();
  }
  filterForm.value.floor = ''
};

/**
 * 新增编辑提交
 */
const handleSubmit = async () => {
  let loading;
  try {
    await formRef.value.validate();
    if (roomTags.value.length == 0) {
      ElMessage.error("选择入住楼层与房间")
      return
    }
    form.enterpriseRoomPojo = [...roomTags.value]
    loading = ElLoading.service({
      lock: true,
      text: '正在初始化页面数据...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const res = await request.post("enterpriseRoom/addEnterpriseRoom", form.enterpriseRoomPojo, {
      params: {
        enterpriseId: form.enterpriseId,
        buildingId: form.buildingId,
        parkId: form.parkId,
        userId: userId.value
      }
    })
    if (res.success) {
      ElMessage.success(res.message)
      dialogVisible.value = false;
      loadRoomData()
      emit('callUpdateLoadAnalysisMethod');
    } else {
      ElMessage.error(res.message)
    }
  } catch (err) {

  } finally {
    if (loading) {
      loading.close()
    }
  }
}


/**
 * 删除
 */
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除当前入住信息吗?')
    .then(() => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.7)',
      })

      request.get('/enterpriseRoom/removeEnterpriseRoom', {
        params: {
          enterpriseId: row.enterpriseId
        }
      }).then(data => {
        if (data.success) {
          ElMessage.success('删除成功');
          loadRoomData()
          emit('callUpdateLoadAnalysisMethod');
        } else {
          ElMessage.error(data.message);
        }
        loading.close()
      }).catch(err => {
        ElMessage.error('删除异常' + err);
        loading.close()
      })
    })
    .catch(() => {
      // catch error
    }).finally(() => {
    })
}

/**
 * ---------------------------------房间信息选择弹框-------------------------------------
 */

const roomDataEditList = ref([])

// 标记：是否正在初始化表格数据（用于忽略初始化时的selection-change）
const isInitializing = ref(false);

const roomTags = ref([])
// 获取表格实例（用于调用toggleRowSelection方法）
const tableRef = ref(null);

const roomDialogVisible = ref(false)
// 筛选条件
const filterForm = ref({
  floor: '',
});

const clickRoom = () => {
  roomDialogVisible.value = true
}
//选择楼层的时候
const handleEditSelectRoomIdChange = async (value) => {
  if (!value) {
    roomDataEditList.value = []
    return
  }
  // 步骤1：标记为初始化状态，忽略此时的selection-change
  isInitializing.value = true;
  const loading = ElLoading.service({
    lock: true,
    text: '正在初始化页面数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const resData = await request.get('/enterpriseRoom/getParkRoom', {
      params: {
        buildingId: form.buildingId,
        floor: value,
        status: 'idle'
      }
    })
    if (resData.success) {
      roomDataEditList.value = resData.data

      // 遍历大数组 roomDataEditList 中的每个元素
      roomDataEditList.value.forEach(bigRoom => {
        // 在小数组 roomTags 中查找 id 相同的元素索引
        const smallRoomIndex = roomTags.value.findIndex(smallRoom => smallRoom.id === bigRoom.id);

        // 若找到相同 id 的元素，则用大数组的元素替换小数组中的对应元素
        if (smallRoomIndex !== -1) {
          // 关键：直接替换引用（而非拷贝），确保后续修改同步
          roomTags.value[smallRoomIndex] = bigRoom;
        }
      });

      // 步骤3：等待表格渲染完成后，从roomTags中恢复当前楼层的选中状态
      await nextTick();
      restoreSelectedState();

      // 步骤4：初始化完成，允许selection-change处理用户操作
      isInitializing.value = false;
    }
  } catch (err) {
    console.log(err, "11111111111111111111")
  } finally {
    loading.close()
  }
}
// 辅助：从roomTags中恢复当前楼层的选中状态
const restoreSelectedState = () => {
  // 清空当前表格选中状态（避免残留）
  tableRef.value.clearSelection();
  // 找出roomTags中属于当前楼层的房间
  const currentFloorSelected = roomTags.value.filter(room =>
    room.floor === filterForm.value.floor
  );

  // 自动勾选这些房间
  currentFloorSelected.forEach(room => {
    const matchedRow = roomDataEditList.value.find(row => row.id === room.id);
    if (matchedRow) {
      tableRef.value.toggleRowSelection(matchedRow, true);
    }
  });
};
// 处理行点击事件：点击行时切换选中状态
const handleRowClick = (row) => {
  // 调用表格实例的toggleRowSelection方法，切换当前行的选中状态
  tableRef.value.toggleRowSelection(row);
}

const handleSelectionChange = (currentSelectedRows) => {
  // 忽略初始化时的空数组触发（避免误删roomTags）
  if (isInitializing.value) return;

  // 当前楼层房间的id集合（用于区分其他楼层房间）
  const currentFloorRoomIds = roomDataEditList.value.map(room => room.id);

  // 步骤1：保留roomTags中“非当前楼层的房间”（不受当前操作影响）
  const otherFloorRooms = roomTags.value.filter(room =>
    !currentFloorRoomIds.includes(room.id)
  );

  // 步骤2：保留当前楼层中“仍被选中”的房间
  const currentFloorSelectedRooms = currentSelectedRows;

  // 步骤3：合并结果（其他楼层房间 + 当前楼层选中房间）→ 去重（基于id）
  const newRoomTags = [...otherFloorRooms];
  currentFloorSelectedRooms.forEach(room => {
    // 只添加新选中且不在newRoomTags中的当前楼层房间
    if (!newRoomTags.some(r => r.id === room.id)) {
      newRoomTags.push(room);
    }
  });
  console.log("00002022")
  // 更新roomTags（仅当前楼层的选中状态变化，其他楼层保留）
  roomTags.value = newRoomTags;

}
//点击删除标签
const handleClose = (id) => {
  // 从roomTags中移除
  roomTags.value = roomTags.value.filter(room => room.id !== id);

  // 若被移除的房间在当前表格中，同步取消选中
  const currentRoom = roomDataEditList.value.find(room => room.id === id);
  if (currentRoom) {
    tableRef.value.toggleRowSelection(currentRoom, false);
  }
}


</script>

<style scoped>
.enterprise-checkin-management {
  padding: 20px;
  background-color: #fff;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 16px;
  text-align: left;
}

/* 房间信息样式优化 */
.room-info-item {
  margin-bottom: 5px;
  padding: 5px 0;
  border-bottom: 1px dashed #eee;
}

.room-info-item:last-child {
  border-bottom: none;
}

.room-name {
  font-weight: 500;
  min-width: 60px;
}

.room-meta {
  color: #666;
  font-size: 13px;
}

/* 房间选择区域样式优化 */
.room-selection-container {
  max-height: 300px;
  overflow-y: auto;
  padding-right: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
}

.room-checkbox {
  width: 100%;
  margin-bottom: 10px;
}

.room-checkbox-content {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}

.room-checkbox-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.room-checkbox-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 0 15px;
  color: #666;
  font-size: 12px;
}

:deep(.el-checkbox__label) {
  width: 100%;
}

:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
}

.filter-form {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  text-align: left;
}
</style>